// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const { productId } = event
  
  if (!productId) {
    return {
      success: false,
      errMsg: '缺少商品ID'
    }
  }
  
  try {
    // 查询与该商品关联的套餐
    const bundlesResult = await db.collection('bundles')
      .where({
        productIds: _.all([productId]),
        status: 'active'
      })
      .orderBy('order', 'asc')
      .get()
    
    return {
      success: true,
      data: bundlesResult.data
    }
  } catch (err) {
    console.error('获取商品套餐失败', err)
    return {
      success: false,
      errMsg: '获取商品套餐失败'
    }
  }
}